<template>
  <el-cascader :options="options" v-model="selects" @change="handleChange" style="width: 100%"> </el-cascader>
</template>

<script setup>
// 省市区级联选择
// https://www.npmjs.com/package/element-china-area-data
import { regionData, provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'

const emits = defineEmits(['change'])
const props = defineProps({
  data: Object,
  dataType: { type: Number, default: 0 }, // 数据类型 0、省市区三级联动 1、省市二级联动
})

const selects = ref([])

watch(
  () => props.data,
  () => {
    selects.value = getCode()
  },
  {
    immediate: true,
  }
)

const options = computed(() => {
  if (props.dataType == 0) return regionData
  else if (props.dataType == 1) return provinceAndCityData
})

const handleChange = (code = []) => {
  props.data.province = CodeToText[code[0]]
  props.data.city = CodeToText[code[1]]
  props.data.district = CodeToText[code[2]]
}

function getCode() {
  let code = []
  const { province, city, district } = props.data

  const provinceCode = province ? TextToCode[province].code : null
  const cityCode = city ? TextToCode[province][city].code : null
  const districtCode = district ? TextToCode[province][city][district].code : null

  if (props.dataType == 0) {
    code = [provinceCode, cityCode, districtCode]
  } else if (props.dataType == 1) {
    code = [provinceCode, cityCode]
  }

  return code
}
</script>

<style></style>
